package com.eatme.core.search;

import com.eatme.core.array.ArrayGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线性查找
 */
public class LinearSearch {
    private static final Logger LOG = LoggerFactory.getLogger(LinearSearch.class);

    private LinearSearch () {
    }

    public static <E> int search(E [] data,E target) {
        for (int i = 0; i < data.length; i++)
            if (data[i].equals(target))
                return i;
        return -1;
    }

    public static void main(String[] args) {
        int[] dataSize = {10000000,100000000};
        for (int n: dataSize) {
            Integer[] data = ArrayGenerator.generateOrderedArray(n);
            long startTime = System.nanoTime();
            int res = -1;
            for (int i = 0; i < 100; i++) {
                res =LinearSearch.search(data, n);
            }
            long endTime = System.nanoTime();
            double time = (endTime-startTime)/1000000000.0;
            System.out.println("n = "+n+", 100 runs : "+time+" s");
            System.out.println(res);
        }
        Integer[] data = {24,18,12,9,16,66,32,4};
        int res2 =LinearSearch.search(data,666);
        System.out.println(res2);

    }
}
